﻿using Mapster;
using SqlSugar;
using Zhp.Common.Exception;
using Zhp.Common.Helper;
using Zhp.Common.WebApp;
using Zhp.Entity.Design;
using Zhp.Entity.Sys;
using Zhp.IService.Design;
using Zhp.Model.Design;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Design
{
    public class DesignListService : BaseService<DesignList>, IDesignListService
    {
        private IBaseRepository<SysMenu> _sysMenuRep;
        private IBaseRepository<SysUserMenu> _sysUserMenuRep;
        public DesignListService(
            IBaseRepository<DesignList> rep,
            ICurrentUser currentUser,
            IBaseRepository<SysMenu> sysMenuRep,
            IBaseRepository<SysUserMenu> sysUserMenuRep)
        {
            _rep = rep;
            _currentUser = currentUser;
            _sysMenuRep = sysMenuRep;
            _sysUserMenuRep = sysUserMenuRep;
        }
        public async Task<List<DesignListModel>> Query(DesignListQuery p)
        {
            var emailList = await _rep.GetPageListAsync(new List<IConditionalModel>
            {

            }, p, x => x.CreateTime, OrderByType.Desc);

            return emailList.Adapt<List<DesignListModel>>();
        }


        public async Task<bool> Create(DesignListEdit p)
        {
            if (await _rep.IsAnyAsync(x => x.Name == p.Name))
            {
                throw new AlertException($"名称：{p.Name}已存在!");
            }
            p.Id = SnowFlakeHelper.GetLongId();
            var entity = p.Adapt<DesignList>();

            //新增菜单信息
            var menu = GenerateSysMenu(p);

            menu.Id = SnowFlakeHelper.GetLongId();
            entity.MenuId = menu.Id;

            //给当前登录人添加菜单权限
            var userMenu = new SysUserMenu
            {
                UserId = _currentUser.UserId,
                MenuId = menu.Id,
                CreateTime = DateTime.Now,
                IsDeleted = false,
            };

            entity.InsertExtraEntity.Add(menu);
            entity.InsertExtraEntity.Add(userMenu);

            return await _rep.InsertAsync(entity);
        }

        private SysMenu GenerateSysMenu(DesignListEdit p)
        {
            string routerUrl = "designInstance/:ListId";
            routerUrl = p.MenuConfig.ParentId.HasValue ? routerUrl : $"/{routerUrl}";
            return new SysMenu
            {
                ParentId = p.MenuConfig.ParentId,
                Name = p.Name,
                MenuType = Entity.SysEnum.MenuTypeEnum.Menu,
                RouterName = $"designInstance_{p.Id}",
                RouterUrl = routerUrl,
                RouterParams = new { ListId = p.Id.ToString() }.ToJson(),
                WebFilePath = "design/designInstance/index",
                Order = p.MenuConfig.Order,
            };
        }

        public async Task<bool> Update(DesignListEdit p)
        {
            if (await _rep.CountAsync(x => x.Id != p.Id && x.Name == p.Name) > 0)
            {
                throw new AlertException($"名称：{p.Name}已存在!");
            }
            var entity = await _rep.GetByIdAsync(p.Id);
            if (entity != null)
            {
                p.Adapt(entity);

                //更新菜单信息
                var menu = GenerateSysMenu(p);
                var exist = await _sysMenuRep.IsAnyAsync(x => x.Id == entity.MenuId);
                if (exist)
                {
                    menu.Id = entity.MenuId;
                    entity.UpdateExtraEntity.Add(menu);
                }
                else
                {
                    menu.Id = SnowFlakeHelper.GetLongId();
                    entity.MenuId = menu.Id;
                    entity.InsertExtraEntity.Add(menu);
                }

                //给当前登录人添加菜单权限
                var userMenu = new SysUserMenu
                {
                    UserId = _currentUser.UserId,
                    MenuId = menu.Id,
                    CreateTime = DateTime.Now,
                    IsDeleted = false,
                };
                var existUserMenu = await _sysUserMenuRep.IsAnyAsync(x => x.UserId == userMenu.UserId && x.MenuId == userMenu.MenuId);
                if (existUserMenu)
                {
                    entity.UpdateExtraEntity.Add(userMenu);
                }
                else
                {
                    entity.InsertExtraEntity.Add(userMenu);
                }

                return await _rep.UpdateAsync(entity);
            }
            return false;
        }

        public async Task<bool> Delete(long id)
        {
            var entity = await _rep.GetByIdAsync(id);
            if (entity != null)
            {
                var menu = await _sysMenuRep.GetByIdAsync(entity.MenuId);
                if (menu != null)
                {
                    entity.DeleteExtraEntity.Add(menu);
                }

                var userMenuList = await _sysUserMenuRep.GetListAsync(x => x.MenuId == entity.MenuId);
                if (userMenuList.Any())
                {
                    entity.DeleteExtraEntity.AddRange(userMenuList);
                }
                return await _rep.DeleteAsync(entity);
            }
            return false;
        }

        public async Task<DesignListEdit> Details(long id)
        {
            var entity = await _rep.GetByIdAsync(id);

            return entity.Adapt<DesignListEdit>();
        }
    }
}
